package com.ruoyi.web.controller.tool;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import java.io.FileInputStream;
import java.io.InputStream;

public class OSSImageUpload {
    // OSS连接参数
    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tBeagSeMrJje1pf7LCj";
    private static final String ACCESS_KEY_SECRET = "X85WnvwbcFm3hPumcwh1GWxgXnBREa";
    private static final String BUCKET_NAME = "aoba-pic";

    public static String uploadImage(String localFilePath, String ossKey) {
        // 1. 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 2. 读取本地图片为输入流
            InputStream inputStream = new FileInputStream(localFilePath);

            // 3. 上传图片到OSS（参数：Bucket名、OSS存储路径、输入流）
            ossClient.putObject(BUCKET_NAME, ossKey, inputStream);

            // 4. 生成图片访问URL（公开Bucket可直接访问，私有Bucket需签名URL）
            return "https://" + BUCKET_NAME + "." + ENDPOINT.replace("https://", "") + "/" + ossKey;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 5. 关闭客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    // 测试上传
    public static void main(String[] args) {
        // 本地图片路径（如：/Users/test/photo.jpg）
        String localPath = "localImagePath";
        // OSS中存储的路径（如：images/2023/10/photo.jpg）
        String ossKey = "images/test.jpg";
        String imageUrl = uploadImage(localPath, ossKey);
        System.out.println("上传成功，图片URL：" + imageUrl);
    }
}
